<template>
  <div class="myBetRecord hideScrollBar">
    <ClientOnly>
      <!-- 导航 -->
      <NavBar
        :title="t('lotteryMoney.wdxz')"
        isFixed
        :isShadow="false"
        @getNavBarHeight="(h) => (pageData.navBarHeight = h)"
      />
      <!-- 工具栏 -->
      <div class="tool items-center">
        <!-- 左边 -->
        <van-tabs
          class="tool-left"
          v-model:active="pageData.menuType"
          line-width="0"
          line-height="0"
          :ellipsis="false"
          @click-tab="onClickTab"
        >
          <!-- 时间 -->
          <van-tab>
            <template #title>
              <div class="items-center tool-time">
                <div class="tool-time-text">{{ selectTime }}</div>
                <img
                  class="tool-time-icon"
                  src="/image/assetDetails/date-jt.svg"
                />
              </div>
            </template>
          </van-tab>
          <!-- 下注记录 -->
          <van-tab>
            <template #title>
              <div
                class="tool-menu-btn"
                :class="{ 'tool-menu-activity': pageData.menuType == 1 }"
              >
                {{ t("lotteryMoney.xzjl") }}
              </div>
            </template>
          </van-tab>
          <!-- 中奖记录 -->
          <van-tab>
            <template #title>
              <div
                class="tool-menu-btn"
                :class="{ 'tool-menu-activity': pageData.menuType == 2 }"
              >
                {{ t("lotteryMoney.zjjl") }}
              </div>
            </template>
          </van-tab>
          <!-- hash pk -->
          <!-- <van-tab>
            <template #title>
              <div class="tool-menu-btn">hash PK</div>
            </template>
          </van-tab> -->
        </van-tabs>
      </div>
      <!-- 内容部分 -->
      <div
        class="contentview hideScrollBar"
        :style="{
          height: `calc(100vh - ${pageData.navBarHeight}px - 44px)`,
        }"
        :class="{
          'contentview-notdata-bg':
            !pageData.loading && pageData.list.length === 0,
        }"
      >
        <!-- 暂无内容 -->
        <div
          v-if="!pageData.loading && pageData.list.length === 0"
          class="contentview-notdata items-center"
        >
          <img class="contentview-notdata-img" src="/image/notdate-icon.png" />
          <div class="contentview-notdata-desc">{{ t("mvp.other.zwnr") }}</div>
        </div>
        <!-- 列表 -->
        <van-list
          v-else
          v-model:loading="pageData.loading"
          :finished="pageData.finished"
          :finished-text="t('mvp.other.text4')"
          :loading-text="t('mvp.other.text11')"
          @load="onLoadList"
        >
          <!-- 列表 -->
          <MybetCell
            style="position: relative; z-index: 9"
            :list="pageData.list"
            :cellType="pageData.menuType"
          ></MybetCell>
        </van-list>
      </div>
      <!-- 圆角弹窗（底部） -->
      <DatePicker
        v-model:show="pageData.isSHowPicker"
        @confirm="confirmTime"
      ></DatePicker>
    </ClientOnly>
  </div>
</template>
<script setup name="myBetRecord">
import { navigateI18nTo } from "@/utils";
import { useGlobalStore } from "~~/store/global";
import { getMyBetRecord, getMyPrizeRecordV3 } from "../../api/lottery";
import { useDateFormat } from "@vueuse/core";
import DatePicker from "../../components/assetDetails/date-picker.vue";
import MybetCell from "@/components/lottery-v3/my-bet-cell.vue";

const { t } = useI18n();
const route = useRoute();
console.log("页面参数:", route.query);

const globalStore = useGlobalStore();
// 如果没有登录-直接跳转登录页面
if (!globalStore.$state.token && process.client) {
  bridge.onAppLogin();
}

// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase

// 页面属性
const pageData = reactive({
  isSHowPicker: false,
  navBarHeight: 0,
  // 上拉加载属性
  loading: false,
  finished: false,
  prefixs: [], // 分类标识
  list: [],
  pageNum: 0,
  total: 0,
  // 筛选项
  startTime: 0,
  endTime: 0,
  menuType: 1, // 1： 下注记录 2： 中奖记录
  selectType: 4, // -1：没有选择  1： 按月  2：按天 3：上个月 4：近3 个月 5：开始时间  6：结束时间
});

const selectTime = computed(() => {
  if (pageData.selectType === 1) {
    return useDateFormat(pageData.startTime, "YYYY.M").value;
  } else if (pageData.selectType === 3) {
    return t("mvp.incomeStatement.sy");
  } else if (pageData.selectType === 4) {
    return t("mvp.zj90t");
  } else if (pageData.selectType === 5 || pageData.selectType === 6) {
    return `${useDateFormat(pageData.startTime, "YYYY.M.D").value}-${
      useDateFormat(pageData.endTime, "YYYY.M.D").value
    }`;
  } else {
    return t("mvp.incomeStatement.default");
  }
});

/**
 * @description: 上啦加载
 * @param {*} isRetry 重试一次
 * @author: zhj1214
 */
const onLoadList = (isRetry) => {
  pageData.pageNum += 1;
  getMyBetRecordRequest((isAdd) => {
    if (!isAdd) {
      pageData.pageNum -= 1;
      if (!isRetry) {
        setTimeout(() => {
          onLoadList(true);
        }, 3000);
      }
    }
  });
};

// 当前数据总和,用来判断是否还需要上啦加载
const recordsTotal = computed(() => {
  let total = 0;
  pageData.list.forEach((yf) => {
    if (yf.list) {
      total += yf.list.length;
    }
  });
  return total;
});

// 获取列表数据
const getMyBetRecordRequest = async (call) => {
  pageData.loading = true;
  let api = pageData.menuType == 1 ? getMyBetRecord : getMyPrizeRecordV3;
  const res = await api({
    beginTime: pageData.startTime,
    endTime: pageData.endTime,
    pageNum: pageData.pageNum,
    pageSize: 20,
  });
  pageData.loading = false;

  console.log("--获取列表数据--", res);
  if (res) {
    if (res.records && res.records.length > 0) {
      res.records.forEach((e) => {
        // e.drawType = 3
        // 1. 加工数据
        const t = useDateFormat(Number(e.drawTime), "YYYY-MM-DD HH:mm:ss");
        e.timeStr = t.value;
        // 2.分类数据: 按天分类
        const prefix = t.value.substring(0, 10);
        if (pageData.prefixs.includes(prefix)) {
          pageData.list.forEach((b) => {
            if (b.months === prefix) {
              b.list.push(e);
            }
          });
        } else {
          pageData.prefixs.push(prefix);
          pageData.list.push({
            months: prefix,
            list: [e],
          });
        }
        return e;
      });
    }

    // console.log("--分类后的数据：", pageData.list);
    // pageData.list = pageData.list.concat(arr);
    pageData.total = res.total;
    if (recordsTotal.value >= res.total) {
      pageData.finished = true;
    } else {
      pageData.finished = false;
    }
    if (res.records && res.records.length > 0) {
      call && call(true);
    } else {
      call && call(false);
    }
  } else {
    pageData.finished = true;
    call && call(false);
  }
};

onBeforeMount(async () => {
  // 1. 默认 3 个月数据
  const begin = new Date(
    Number(globalStore.$state.serverTime) - 3 * 30 * 24 * 60 * 60 * 1000
  );
  // 设置开始时间是 90 前,那一天的 23 点 59 分 59 秒
  pageData.startTime = new Date(
    `${begin.getFullYear()}/${begin.getMonth() + 1}/${begin.getDate()} 23:59:59`
  ).getTime();

  // 结束时间是此时此刻
  pageData.endTime = Number(globalStore.$state.serverTime); // curt.getTime(); 使用服务器时间

  // console.log(
  //   "--开始时间--",
  //   useDateFormat(Number(pageData.startTime), "YYYY-MM-DD HH:mm:ss").value
  // );
  // 2.1 最大查询时间跨度 6 个月; 修改选择的时间范围,开始时间
  // const minStart = new Date(
  //   Number(globalStore.$state.serverTime) - 6 * 30 * 24 * 60 * 60 * 1000
  // );
  // startTimestamp.value = new Date(
  //   `${minStart.getFullYear()}/${
  //     minStart.getMonth() + 1
  //   }/${minStart.getDate()} 23:59:00`
  // ).getTime();
});

onMounted(() => {
  // 1. 埋点访问
  firebase?.logEvent("BDC_H5_lotteryv3_MyBet_PUV");
  // 2. 请求数据
  onLoadList();
});
onBeforeUnmount(() => {
  isSHowPicker_watch && isSHowPicker_watch();
});

// 下注记录,中奖记录
let menuTypeLast = 1; // 上一次选中的记录索引
const menuTypeChange = (val) => {
  // 1. 是否重置数据
  if (val !== menuTypeLast) {
    pageData.list = [];
    pageData.prefixs = [];
    pageData.finished = false;
  } else {
    return;
  }
  // 2. 赋值、请求新数据
  pageData.pageNum = 1;
  menuTypeLast = val;
  getMyBetRecordRequest();
};

/**
 * @description: tab 切换
 */
const onClickTab = (val) => {
  // console.log("val:", val);
  if (val.name == 0) {
    pageData.isSHowPicker = true;
  } else if (val.name == 3) {
    jumpPage();
  } else if (val.name > 0) {
    menuTypeChange(Number(val.name));
  }
};

// 弹窗确认筛选时间
const confirmTime = ({ start, end, type }) => {
  // 1. 如果没有选择时间，则不做任何改变
  if (start === 0 || end === 0) return;
  // 2. 赋值属性
  pageData.list = [];
  pageData.prefixs = [];
  pageData.startTime = start;
  pageData.endTime = end;
  pageData.pageNum = 1;
  pageData.selectType = type;
  pageData.finished = false;
  pageData.menuType = menuTypeLast;
  // 3. 请求接口
  getMyBetRecordRequest();
};
// 监听弹窗显示,当弹窗关闭的时候,回显 tabs 的选中索引
const isSHowPicker_watch = watch(
  () => pageData.isSHowPicker,
  (newVal) => {
    if (!newVal) {
      pageData.menuType = menuTypeLast;
    }
  }
);

const jumpPage = () => {
  firebase?.logEvent("BDC_H5_V3_Jump_MyBetRecord_PUV");
  navigateI18nTo({
    path: "/lottery-money/my-bet-record",
    query: {
      sessionId: route.query.sessionId,
    },
  });
};
</script>
<style lang="scss" scoped>
.myBetRecord {
  min-height: 100vh;
  background-color: #f4f5f7;

  .tool {
    position: relative;
    width: 100vw;
    height: 42 * 2px;
    background-color: #fff;

    &-time {
      padding-left: 8 * 2px;

      &-text {
        font-size: 12 * 2px;
        color: #007bff;
        font-weight: 650;
        white-space: nowrap;
      }

      &-icon {
        width: 10 * 2px;
        height: 10 * 2px;
        margin: 0 5 * 2px;
      }
    }
    &-menu {
      flex: 1;
      border-left: 1 * 2px solid #f5f5f5;
      padding-left: 5 * 2px;
      font-weight: 600;
      &-btn {
        text-wrap: nowrap;
        white-space: nowrap;
        font-size: 12 * 2px;
        color: #141924;
        padding: 6px 8 * 2px;
      }
      &-activity {
        color: #007bff !important;
        background-color: #ecf5ff !important;
        border-radius: 4 * 2px;
      }
    }

    &-left {
      width: 100vw;
      :deep(.van-tab--grow) {
        padding: 0 8px;
      }
    }
  }
  .contentview {
    padding-bottom: var(--safe-area-inset-bottom);
    background-color: #f4f5f7;
    overflow-y: scroll;
    position: relative;
    &-header {
      padding: 16 * 2px 16 * 2px 0 16 * 2px;
      // margin-top: 10 * 2px;
      position: relative;
      top: 20px;
      height: 78 * 2px;
      z-index: 8;
      &-text {
        margin-top: 10 * 2px;
        color: #141924;
        font-size: 15 * 2px;
        font-weight: 590;
        letter-spacing: -0.8px;
      }
      &-left {
        position: relative;
        &-text {
          color: #141924;
          font-size: 13 * 2px;
          font-weight: 590;
          letter-spacing: -0.8px;
        }
        &-img {
          width: 16 * 2px;
          height: 16 * 2px;
          margin-right: 5 * 2px;
        }
      }
      &-img {
        border-top-right-radius: 12 * 2px;
        border-top-left-radius: 12 * 2px;
        position: absolute;
        top: 0;
        left: 0;
        // height: 107 * 2px;
      }
    }
    &-notdata {
      justify-content: center;
      flex-direction: column;
      position: relative;
      top: 120 * 2px;
      &-img {
        width: 200 * 2px;
        height: 200 * 2px;
      }
      &-desc {
        margin-top: -35 * 2px;
        color: #999da7;
        font-size: 13 * 2px;
      }
      &-bg {
        background-color: #fff !important;
      }
    }
  }
}
</style>
